/**
 * @class UI-多语言文本
 * @author DuskyHuang 圣子
*/

import { _decorator, Component, Label } from 'cc';
import { EDITOR } from 'cc/env';
import { getI18nConfig } from 'helpers';
import { ui } from 'proxies';
const { ccclass, disallowMultiple, requireComponent, property, executeInEditMode } = _decorator;

@ccclass('cocosmos.label-i18n')
@disallowMultiple
@executeInEditMode(true)
@requireComponent(Label)
export class LabelI18n extends Component {

    @property
    private _key: string = null;

    @property
    public get string(): string { return this._label?.string ?? ''; }
    public set string(en: string) {
        const key = en.toLowerCase();
        if (EDITOR) {
            // this._key = key;
            if (!this._label) this._label = this.getComponent(Label);
            this._label.string = en;
        } else {
            this._config = getI18nConfig(en);
            if (!this._config) {
                console.warn('i18n lost config for:', en);
                this._label.string = en;
                return;
            }
        }
        this._key = key;
        this._lang = null;
    }

    public set config(arg: i18nConfig) {
        this._config = arg;
        this._key = arg.en.toLowerCase();
        this._lang = null;
    }

    protected onLoad(): void {
        this._label = this.getComponent(Label);
    }

    protected start(): void {
        if (!EDITOR && this._key && !this._config) {
            this.string = this._key;
        }
    }

    protected lateUpdate(): void {
        if (!EDITOR && this._key) {
            ui.language != this._lang && this._updateString();
        }
    }

    private _updateString(): void {
        this._lang = ui.language;
        if (this._config) {
            this._label.string = this._config[this._lang];
        }
    }

    private _label: Label;
    private _lang: language;
    private _config: i18nConfig;
}